package com.example.sinoyd.frameapplication.KotlinFrame

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import com.example.sinoyd.frameapplication.KotlinFrame.Dataclass.Tabframe
import com.example.sinoyd.frameapplication.KotlinFrame.Uitl.dip2px
import com.example.sinoyd.frameapplication.ProjectCodes.Fragment.*
import com.example.sinoyd.frameapplication.R
import com.sinoyd.Code.Until.SharedPreferencesFactory
import com.tandong.switchlayout.SwichLayoutInterFace
import com.tandong.switchlayout.SwitchLayout
import kotlinx.android.synthetic.main.frame_activity_main.*


class MainActivity : AppCompatActivity(), SwichLayoutInterFace {
    override fun setEnterSwichLayout() {
        SwitchLayout.get3DRotateFromLeft(this, false, null)
    }

    override fun setExitSwichLayout() {
        SwitchLayout.get3DRotateFromRight(this, true, null)
    }

    var tabfragments: ArrayList<Tabframe> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {

        //强制设置竖屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        super.onCreate(savedInstanceState)
        setContentView(R.layout.frame_activity_main)
        setbottomtab()
        setbottomtitlestyle()
        setDefaultFragment()
        setEnterSwichLayout()
    }

    override fun onDestroy() {
        super.onDestroy()
        setExitSwichLayout()
    }

    private fun setbottomtab() {
        tabfragments = ArrayList()
        //判断系统属于气or水
        when (SharedPreferencesFactory.getdata(this, "OS")) {
        //气系统
            "air" -> {
                tabfragments.add(Tabframe(R.mipmap.icon_tab_online, "在线情况", OnlineFragment("在线情况")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_realtime, "实时监测", RealTimeMonitoringFragment("实时监测")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_alrm, "报警信息", AlarmInformationFragment("报警信息")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_aqi, "AQI指数", AQIFragment("AQI指数")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_qushi, "趋势分析", TrendAnalysisFragment("趋势分析")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_gis, "GIS监控", GisFragment("GIS监控")))
            }
        //水系统
            "water" -> {
                tabfragments.add(Tabframe(R.mipmap.icon_tab_online, "在线情况", OnlineFragment("在线情况")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_realtime, "实时监测", RealTimeMonitoringFragment("实时监测")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_alrm, "报警信息", AlarmInformationFragment("报警信息")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_qushi, "水质趋势", TrendAnalysisFragment("水质趋势")))
                tabfragments.add(Tabframe(R.mipmap.icon_tab_gis, "GIS监控", GisFragment("GIS监控")))
            }
        }

        tabfragments.add(Tabframe(R.mipmap.icon_tab_more, "关于", AboutFragment("关于")))

    }

    //设置默认的Fragment   默认第一个界面"0"
    private fun setDefaultFragment() {
        val fm = fragmentManager
        val transaction = fm.beginTransaction()
        transaction.replace(R.id.frgContent, tabfragments[0].frame)
        transaction.commit()
    }


    //设置底部导航栏风格及参数
    private fun setbottomtitlestyle() {
        for (item in tabfragments) {
            bottom_navigation_bar.addItem(BottomNavigationItem(item.imageid, item.titlename))
        }

        //当底部导航个数大于5个的时候 设置滑动 [反射]
        if (tabfragments.size > 3) {
//            //暴力修改private属性【setScrollable方法】
            try {
                val clazz = Class.forName("com.ashokvarma.bottomnavigation.BottomNavigationBar")
                //得到setScrollable方法
                val method = clazz.getDeclaredMethod("setScrollable", Boolean::class.java)
                //调用方法
                method.isAccessible = true
                method.invoke(bottom_navigation_bar, true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        bottom_navigation_bar
                .setMode(BottomNavigationBar.MODE_FIXED)
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC)
                .setTabSelectedListener(object : BottomNavigationBar.OnTabSelectedListener {
                    override fun onTabReselected(position: Int) {
                        //重新被选中
                    }

                    override fun onTabUnselected(position: Int) {
                        //未被选中
                    }

                    override fun onTabSelected(position: Int) {
                        //选中
                        val fm = fragmentManager
                        val transaction = fm.beginTransaction()
                        transaction.replace(R.id.frgContent, tabfragments[position].frame)
                        transaction.commit()
                    }
                })

                .setActiveColor("#FF9224") //选中颜色
                .setInActiveColor("#FFFFFF") //未选中颜色
                .setBarBackgroundColor("#0f82ff")//导航栏背景色
                .setFirstSelectedPosition(0)//默认的位置
//              .setScrollable(true)//滑动设置，暂时版本还未开放
                .initialise()

        runOnUiThread {
            setBottomNavigationItem(bottom_navigation_bar, 6, 30, 12)
        }
    }


    private fun setBottomNavigationItem(bottomNavigationBar: BottomNavigationBar, space: Int, imgLen: Int, textSize: Int) {
        val barClass = bottomNavigationBar.javaClass
        val fields = barClass.declaredFields
        for (i in fields.indices) {
            val field = fields[i]
            field.isAccessible = true
            if (field.name.equals("mTabContainer")) {
                try {
                    //反射得到 mTabContainer
                    val mTabContainer = field.get(bottomNavigationBar) as LinearLayout
                    for (j in 0 until mTabContainer.childCount) {
                        //获取到容器内的各个Tab
                        val view = mTabContainer.getChildAt(j)
                        //获取到Tab内的各个显示控件
                        var params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(this, 56.toFloat()))
                        val container = view.findViewById<FrameLayout>(R.id.fixed_bottom_navigation_container)
                        container.layoutParams = params
                        container.setPadding(dip2px(this, 12.toFloat()), dip2px(this, 0.toFloat()), dip2px(this, 12.toFloat()), dip2px(this, 0.toFloat()))

                        //获取到Tab内的文字控件
                        val labelView = view.findViewById<TextView>(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_title)
                        //计算文字的高度DP值并设置，setTextSize为设置文字正方形的对角线长度，所以：文字高度（总内容高度减去间距和图片高度）*根号2即为对角线长度，此处用DP值，设置该值即可。
                        labelView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize.toFloat())
                        labelView.includeFontPadding = false
                        labelView.setPadding(0, 0, 0, dip2px(this, (20 - textSize - space / 2).toFloat()))

                        //获取到Tab内的图像控件
                        val iconView = view.findViewById<ImageView>(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_icon)
                        //设置图片参数，其中，MethodUtils.dip2px()：换算dp值
                        params = FrameLayout.LayoutParams(dip2px(this, imgLen.toFloat()), dip2px(this, imgLen.toFloat()))
                        params.setMargins(0, 0, 0, space / 2)
                        params.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                        iconView.scaleType = ImageView.ScaleType.CENTER_INSIDE
                        iconView.layoutParams = params
                    }
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                }

            }
        }
    }
}
